package com.example.huixingzheng.dao;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MqttDataForwarder {
    private static final String SERVER_URI = "tcp://your_mqtt_server_uri:1883";  // 替换为实际的 MQTT 服务器地址和端口
    private static final String CLIENT_ID = "data_forwarder_client";
    private static final String SUBSCRIBE_TOPIC = "source_topic";  // 要订阅的源主题
    private static final String PUBLISH_TOPIC = "target_topic";  // 要发布到的目标主题

    private MqttClient client;

    public MqttDataForwarder() throws MqttException {
        client = new MqttClient(SERVER_URI, CLIENT_ID, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        client.connect(options);
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.err.println("连接丢失: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                System.out.println("接收到消息: " + new String(message.getPayload()) + " 来自主题: " + topic);
                // 将接收到的消息发布到目标主题
                MqttMessage publishMessage = new MqttMessage(message.getPayload());
                client.publish(PUBLISH_TOPIC, publishMessage);
                System.out.println("已将消息转发到主题: " + PUBLISH_TOPIC);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("消息传递完成");
            }
        });
        client.subscribe(SUBSCRIBE_TOPIC);
    }

    public static void main(String[] args) {
        try {
            MqttDataForwarder forwarder = new MqttDataForwarder();
            System.out.println("数据转发器已启动，等待接收和转发消息...");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}